package net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.Charset;

public class MyChatClient {
	private int port = 9099;
	private OutputStream out;
	private InputStream in;
	private Socket socket;
	private boolean isAlive = true;
	
	public void connect(){
		try {
			socket = new Socket("127.0.0.1", port);
			in = socket.getInputStream();
			out = socket.getOutputStream();
			
			//Start reading thread
			Thread t = new Thread(new ClientService());
			t.start();
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	synchronized void handleMessage(String msg){
		System.out.println(msg);
	}
	
	public void sendMessage(String msg){
		try {
			out.write(msg.getBytes(Charset.forName("utf-8")));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	class ClientService implements Runnable{
		public void run(){
			int read;
			byte[] buf = new byte[512];
			try{
				while( (read = in.read(buf))>0 && isAlive ){
					handleMessage(new String(buf, 0, read, Charset.forName("utf-8")));
				}
			}catch(IOException ex){}
		}
	}
}
